import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:xindong/common/xindong_sezhi.dart';
import 'package:xindong/common/xindong_define.dart';
import 'package:xindong/common/xindong_all.dart';
import 'package:xindong/common/xindong_methods.dart';
import 'package:xindong/res/assets_res.dart';
import 'package:xindong/routes/call/controller/xindong_call_controller.dart';
import 'package:xindong/routes/call/controller/xindong_call_rtc_controller.dart';
import 'package:xindong/routes/call/dialog/xindong_call_action_button.dart';
import 'package:xindong/routes/call/view/xindong_call_rtc_video_preview.dart';
import 'package:xindong/utils/xindong_calender_util.dart';
import 'package:xindong/utils/xindong_image_util.dart';
import 'package:xindong/utils/xindong_text_util.dart';
import 'package:xindong/widgets/common/xindong_app_bar.dart';
import 'package:xindong/widgets/xindong_avatar.dart';
import 'package:xindong/widgets/xindong_common_burn_layer.dart';

// 悬浮   呼叫/等待接听中
class XinDongCallWaitingDialog {
  // ======== 单例
  // 工厂方法构造函数
  factory XinDongCallWaitingDialog() => _getInstance();

  // instance的getter方法，singletonManager.instance获取对象
  static XinDongCallWaitingDialog get instance => _getInstance();

  // 静态变量_instance，存储唯一对象
  static XinDongCallWaitingDialog? _instance;

  // 获取对象
  static XinDongCallWaitingDialog _getInstance() {
    _instance ??= XinDongCallWaitingDialog._internal();
    return _instance!;
  }

  // 私有的自定义命名式构造方法，通过它实现一个类;
  // 子类不能继承internal
  // 不是关键字，可定义其他名字
  XinDongCallWaitingDialog._internal() {
    // 初始化(设置一些默认的)...
  }

  // 唯一标识
  final String tag = "kTagCallWaiting";

  void show({required Function() onAccept, required Function() onReject, required Function() onCancel}) {
    // 等待初始化之后再调用
    if (XinDongAll.instance.smartDialogInitialized == false) {
      Future.delayed(const Duration(seconds: 2)).whenComplete(() async {
        show(onAccept: onAccept, onReject: onReject, onCancel: onCancel);
      });
      return;
    }
    SmartDialog.show(
      tag: tag,
      alignment: Alignment.bottomCenter,
      animationTime: const Duration(milliseconds: 260),
      animationType: SmartAnimationType.centerScale_otherSlide,
      backDismiss: false,
      // false点击不隐藏
      clickMaskDismiss: false,
      // 不显示动画
      useAnimation: true,
      builder: (BuildContext context) {
        return XinDongCallWaitingView(
          onAccept: onAccept,
          onRefuse: onReject,
          onCancel: onCancel,
        );
      },
    );
  }

  void hide() {
    try {
      SmartDialog.dismiss(status: SmartStatus.custom, tag: tag);
    } catch (error) {
      mCatchPrint(error);
    }
  }
}

// 1v1 见面等待中
// 发起方 可挂断
// 接受方 可挂断、可接听
class XinDongCallWaitingView extends StatelessWidget {
  final Function() onAccept;
  final Function() onRefuse;
  final Function() onCancel;

  const XinDongCallWaitingView({Key? key, required this.onAccept, required this.onRefuse, required this.onCancel})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    final controller = XinDongCallController.to;
    return Container(
      color: Colors.grey.shade900,
      child: Stack(
        fit: StackFit.expand,
        children: [
          // 只为状态栏设置
          XinDongAppBar(
            "",
            brightness: Brightness.dark,
            toolbarHeight: 0,
            automaticallyImplyLeading: false,
            backgroundColor: Colors.transparent,
            elevation: 0,
          ),

          // 背景主题图
          // ImageUtil.avatarUrl(controller.targetUser.getAvatar),
          ImageUtil.asset(AssetsRes.DEFAULT_SPLASH),

          // 毛玻璃层
          const XinDongCommonBurnLayer(opacity: 0.5, color: Colors.black45),

          // 视频预览
          if (XinDongCallController.to.currentCallType == XinDongCallType.videoCall) const XinDongCallRTCVideoPreview(),

          // 用户信息
          Container(
            child: controller.isMineInvite
                ? _buildContainerMineInviteInfo(controller)
                : _buildContainerMineInvitedInfo(controller),
          ),
        ],
      ),
    );
  }

  // 我被邀请的
  Widget _buildContainerMineInvitedInfo(XinDongCallController controller) {
    return Column(
      children: [
        SizedBox(height: 44 + screenHeight > 667 ? 96 : 60),

        // 头像
        XinDongAvatarBorder(controller.targetUser, avatarSize: 96.0, borderWidth: 2.0),

        const SizedBox(height: 24),

        // 昵称
        Text(
          controller.targetUser.getName,
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
          style: const TextStyle(fontSize: 22, color: Colors.white, fontWeight: FontWeight.bold),
        ),
        const SizedBox(height: 8),
        // Row(
        //   mainAxisSize: MainAxisSize.min,
        //   children: [
        //     ImageHelper.asset(AssetsRes.ICON_GOLD_COIN, width: 14, height: 14),
        //     const SizedBox(width: 5),
        //     Text(
        //       "${controller.currentPrice}金币/分钟",
        //       style: const TextStyle(fontSize: 12, color: Colors.white70, fontWeight: FontWeight.normal),
        //     ),
        //   ],
        // ),
        const SizedBox(height: 8),
        Text(
          controller.showConnectingText,
          style: const TextStyle(fontSize: 16, color: Colors.white70, fontWeight: FontWeight.normal),
        ),
        GetBuilder<XinDongCallController>(builder: (controller) {
          return Text(
            "等待时长：${XinDongCalendarUtil.timeTextHMS(controller.connectingTimeCount)}",
            style: const TextStyle(fontSize: 12, color: Colors.white70, fontWeight: FontWeight.normal),
          );
        }),
        const Expanded(child: SizedBox()),

        // 通话提示
        _buildContainerTips(),

        // 挂断
        _buildActionButton(controller),
        SizedBox(height: 60 + bottomBarHeight),
      ],
    );
  }

  // 我邀请的
  Widget _buildContainerMineInviteInfo(XinDongCallController controller) {
    return Column(
      children: [
        const SizedBox(height: 24 + 44),
        Row(
          children: [
            const SizedBox(width: 16),
            XinDongAvatarBorder(controller.targetUser, avatarSize: 64.0, borderWidth: 2.0),
            const SizedBox(width: 16),
            Flexible(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    controller.targetUser.getName,
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: const TextStyle(fontSize: 16, color: Colors.white, fontWeight: FontWeight.bold),
                  ),
                  const SizedBox(height: 4),
                  // Row(
                  //   mainAxisSize: MainAxisSize.min,
                  //   children: [
                  //     ImageHelper.asset(AssetsRes.ICON_GOLD_COIN, width: 14, height: 14),
                  //     const SizedBox(width: 5),
                  //     Text(
                  //       "${controller.currentPrice}金币/分钟",
                  //       style: const TextStyle(fontSize: 12, color: Colors.white, fontWeight: FontWeight.w400),
                  //     ),
                  //   ],
                  // ),
                  const SizedBox(height: 4),
                  Text(
                    controller.showConnectingText,
                    style: const TextStyle(fontSize: 12, color: Colors.white60, fontWeight: FontWeight.w400),
                  ),
                ],
              ),
            )
          ],
        ),
        const Expanded(child: SizedBox()),

        Padding(
          padding: const EdgeInsets.all(20.0),
          child: GetBuilder<XinDongCallController>(builder: (controller) {
            return Text(
              "等待时长：${XinDongCalendarUtil.timeTextHMS(controller.connectingTimeCount)}",
              style: const TextStyle(fontSize: 12, color: Colors.white70, fontWeight: FontWeight.normal),
            );
          }),
        ),

        // 通话提示
        _buildContainerTips(),

        // 挂断
        _buildActionButton(controller),
        SizedBox(height: 60 + bottomBarHeight),
      ],
    );
  }

  // 通话提示
  Widget _buildContainerTips() {
    return GetBuilder<XinDongCallController>(builder: (controller) {
      if (TextUtil.isEmpty(controller.showStatusTipsText)) {
        return const SizedBox();
      }
      return Container(
        height: 32.0,
        padding: const EdgeInsets.only(left: 16, right: 16),
        margin: const EdgeInsets.only(bottom: 20),
        decoration: BoxDecoration(
          color: Colors.black26,
          borderRadius: BorderRadius.circular(32),
        ),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(
              controller.showStatusTipsText,
              style: const TextStyle(fontSize: 16, fontWeight: FontWeight.normal, color: Colors.white, height: 1.2),
            ),
          ],
        ),
      );
    });
  }

  // 按钮
  // 我邀请的 -挂断
  // 我被邀请 -拒绝/接受
  Widget _buildActionButton(XinDongCallController controller) {
    if (controller.isMineInvite) {
      // 挂断
      return Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          XinDongCallActionButton(
            size: 64.0,
            icon: ImageUtil.asset(AssetsRes.BUTTON_HANGUP),
            onPressed: onCancel,
          ),
          const Padding(
            padding: EdgeInsets.only(top: 10.0),
            child: Text("挂断", style: TextStyle(color: Colors.white, fontSize: 14)),
          ),
        ],
      );
    } else {
      // 拒绝/接受
      return Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Column(
            children: [
              XinDongCallActionButton(
                size: 64.0,
                icon: ImageUtil.asset(AssetsRes.BUTTON_HANGUP),
                onPressed: onRefuse,
              ),
              const Padding(
                padding: EdgeInsets.only(top: 10.0),
                child: Text("挂断", style: TextStyle(color: Colors.white, fontSize: 14)),
              ),
            ],
          ),
          Column(
            mainAxisAlignment: MainAxisAlignment.end,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              XinDongCallActionButton(
                size: 64,
                icon: ImageUtil.asset(AssetsRes.BUTTON_ACCEPT),
                onPressed: onAccept,
              ),
              const Padding(
                padding: EdgeInsets.only(top: 10.0),
                child: Text("接听", style: TextStyle(color: Colors.white, fontSize: 14)),
              ),
            ],
          ),
        ],
      );
    }
  }
}
